﻿using Light.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Com.CMB
{
    /// <summary>
    /// 类名：Core
    /// 功能：一网通接口公用函数类
    /// 详细：该类是请求、通知返回两个文件所调用的公用函数核心处理文件，不需要修改
    /// 版本：3.4
    /// 修改日期：2016-10-17
    /// 说明：
    /// 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
    /// 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
    /// </summary>
    public class Core
    {
        public Core()
        {

        }
        /// <summary>
        /// 除去数组中的空值和签名参数并以字母a到z的顺序排序
        /// </summary>
        /// <param name="dicArrayPre">过滤前的参数组</param>
        /// <returns>过滤后的参数组</returns>
        public static Dictionary<string, string> FilterPara(SortedDictionary<string, string> dicArrayPre)
        {
            Dictionary<string, string> dicArray = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> temp in dicArrayPre)
            {
                if (temp.Key.ToLower() != "sign" && temp.Key.ToLower() != "sign_type" && temp.Value != "" && temp.Value != null)
                {
                    dicArray.Add(temp.Key, temp.Value);
                }
            }

            return dicArray;
        }

        /// <summary>
        /// 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
        /// </summary>
        /// <param name="sWord">要写入日志里的文本内容</param>
        public static void LogResult(string sWord)
        {
            string strPath = Config.log_path + "\\" + "CMB_log_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            StreamWriter fs = new StreamWriter(strPath, false, System.Text.Encoding.Default);
            fs.Write(sWord);
            fs.Close();
        }
        /// <summary>
        /// 获取文件的md5摘要
        /// </summary>
        /// <param name="sFile">文件流</param>
        /// <returns>MD5摘要结果</returns>
        public static string GetAbstractToMD5(Stream sFile)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(sFile);
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 获取文件的md5摘要
        /// </summary>
        /// <param name="dataFile">文件流</param>
        /// <returns>MD5摘要结果</returns>
        public static string GetAbstractToMD5(byte[] dataFile)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(dataFile);
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public  static T GetDeserialize<T>(string jsonString)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }
        /// <summary>
        /// Base64解密，采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(string result)
        {
            return DecodeBase64(Encoding.UTF8, result);
        }
        public static string DecodeBase64(Encoding encode, string result)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }

        public static string GetMerchantCode(string strKey,string strDate, string strBranchID, string strCono, string strBillNo,
            string strAmount, string strMerchantPara, string strMerchantUrl, string PNo, string MchNo, string BindCardUrl, string BindCardPara, string Mobile, string Longitude, string Dimension, string PayerID, string PayeeID)
        {
            string strGoodsType = "54011600";
            string strPayerID = PayerID;
            string strPayeeID = PayeeID;
            string strClientIP = WebHelper.GetCurrentRequestIP();//"127.0.0.1"

            //暂时调用自动生成code
            string strReserved = "<Protocol>";
            strReserved += "<PNo>" + PNo + "</PNo>";//客户协议号
            strReserved += "<TS>" + DateTime.Now.ToString("yyyyMMddHHmmss") + "</TS>";//交易时间
            strReserved += "<MchNo>" + MchNo + "</MchNo>";//协议商户企业编号
            strReserved += "<Seq>" + DateTime.Now.ToString("HHMMssfffyyyyMMdd") + "</Seq>";//协议开通请求流水号 开通协议时非空
            strReserved += "<URL>" + BindCardUrl + "</URL>";//协议开通结果通知命令请求地址 绑卡地址
            strReserved += "<Para>" + BindCardPara + "</Para>";//协议开通结果通知命令参数 |
            strReserved += "<MUID></MUID>";//协议用户ID
            strReserved += "<Mobile>" + Mobile + "</Mobile>";//协议手机号
            strReserved += "<LBS>" + Longitude + "|" + Dimension + "</LBS>";//地理位置 经度|纬度
            strReserved += "<RskLvl></RskLvl>";//客户风险等级
            strReserved += "</Protocol>";
            return Light.Utility.CMB.OneNetPayHelper.GetMerchantCode(strKey, strDate, strBranchID, strCono, strBillNo, strAmount, strMerchantPara, strMerchantUrl, strPayerID, strPayeeID, strClientIP, strGoodsType, strReserved);

        }
    }
}
